package org.jypj.dev.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordUtil {

	protected static Log logger = LogFactory.getLog(WordUtil.class);
	/**
	 * 生成word文档 先创建一个wrod 然后编辑模板，另存为xml文件，使用模板ftl生成xml文件，将后缀名改为docx即可
	 * @param dataMap 要生成的模板数据
	 * @param ftlPath 模板文件的地址
	 * @param ftlName 模板文件的名称
	 * @param filePath 要生成的文件路径
	 * @param fileName 要生成的文件的名称
	 * @throws Exception
	 */
	public static void createWord(Map<String, Object> dataMap,String ftlPath,String ftlName,String filePath,String fileName) throws Exception {
		PathUtil.Path_Judge_Exist(filePath);// 判断生成的地址是否存在不存在就创建
		Configuration cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(ftlPath));// 创建配置对象
		Template template = cfg.getTemplate(ftlName, "utf-8"); // 得到模板对象
		PathUtil.printFileByObject(dataMap, template, filePath, fileName);
	}
	
	/**
	 * 
	 * 用于导出保存excel方法
	 * @param response
	 * @param excelName：文件名称，可为中文
	 * @param filePath：从服务器获取文件全路径
	 */
	public static void outputWord(HttpServletResponse response, String wordName,
			String filePath) {
		try {
			
			response.reset();
			response.setContentType("application/msword");
			
			//Word对应的就是 application/msword
			String fileName = new String(wordName.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName);
			filePath=filePath+"/"+wordName;
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(new FileInputStream(filePath));
				bos = new BufferedOutputStream(response.getOutputStream());
				
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
				bos.flush();
				
			} catch (final IOException e) {
				e.printStackTrace();
				logger.debug("出现IOException." + e.getMessage());
			} finally {
				if (bis != null){
					bis.close();
					bis = null;
				}
				if (bos != null){
					bos.close();
					bos = null;
				}
			}
			return;
		} catch (Exception e) {
			logger.debug(e);
		}
	}
}
